﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Collections;
using System.IO;
using MG_POS_PC.Model;

namespace MG_POS_PC.Util
{
    public class SocketUtil
    {
        private int bufferSize = 1024;
        private List<SocketResponse> sResList;
        private SocketResponse bean;

        public  List<SocketResponse> communicate(string strIP, string strPort, List<SocketRequest> sReqList)
        {
            try
            {
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                string ipAdress = strIP;
                int port = Convert.ToInt16(strPort);
                client.Connect(ipAdress, port);

                sResList = new List<SocketResponse>();
                foreach (SocketRequest sr in sReqList)
                {
                    bean = new SocketResponse();
                    string msg = JsonTools.ObjectToJson(sr);
                    client.Send(Encoding.UTF8.GetBytes(msg + "\r\n"));
                    int tempCount = 0;
                    StringBuilder sb = new StringBuilder();
                    ArrayList al = new ArrayList();


                    int count = 0;
                    do
                    {
                        byte[] tempBuf = new byte[bufferSize];
                        count = client.Receive(tempBuf);
                        tempCount += count;
                        byte[] recvBuf = new byte[count];
                        Buffer.BlockCopy(tempBuf, 0, recvBuf, 0, count);
                        al.Add(recvBuf);
                    } while (count == bufferSize);

                    byte[] revBuf = new byte[tempCount];
                    count = 0;
                    for (int i = 0; i < al.Count; i++)
                    {
                        byte[] item = (byte[])al[i];
                        item.CopyTo(revBuf, count);
                        count += item.Length;
                    }

                    string context = Encoding.UTF8.GetString(revBuf);
                    sResList.Add((SocketResponse)JsonTools.JsonToObject(context, bean));
                }
                return sResList;
            }
            catch (System.Exception ex)
            {
                writeLog(ex.Message);
                return null;
            }

        }

       


        public void writeLog(string mess)
        {
            FileStream fs = new FileStream(@"c:/mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" -->" + mess);
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
        }
    }
}
